package com.ids.enigha;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Typeface;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.ids.enigha.R;

public class LoginPage extends Activity {

	Button loginbtn, registerbtn;
	public static String NAME = "enigha";
	public static String UNAME = "USERNAME";
	public static String PASS = "PASSWORD";
	public static String DEVID = "DEVICE_ID";
	public static String DEVNAME = "DEVICE_NAME";
	public static String URL_PATH = "http://192.237.167.247:9090/eNigha-trackingserver-1.0-SNAPSHOT/devices";

	String username = null;
	String password = null;
	String deviceid = null;
	
	String installedDate, expDate, currentDate, alertMsg;
	Typeface face;
	
	EditText usernameet, passwordet;
	String userString, passString, timervalue, edittimervalue;
	public static int timerval;
	SharedPreferences sharedprefs;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.loginpage);

		usernameet = (EditText) findViewById(R.id.username_edittext);
		passwordet = (EditText) findViewById(R.id.password_edittext);

		loginbtn = (Button) findViewById(R.id.login_btn);
		registerbtn = (Button) findViewById(R.id.register_btn);
		
		if(isTrackingStarted())
		{
			loginbtn.setText("Logout");
			//passwordet.setEnabled(false);
			passwordet.setVisibility(View.INVISIBLE);
		}

		Log.d(UNAME, "name usernaem=" + username);
		Log.d(UNAME, "name password=" + password);
		Log.d(UNAME, "name deviceid=" + deviceid);
		face = Typeface.createFromAsset(this.getAssets(), "FrancoisOne.ttf");
		
		if(!isGPSEnabled())
		{
			try
			{
				Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
				intent.putExtra("enabled", true);
				sendBroadcast(intent);
				turnGPSOn();
			}
			catch(Exception ex)
			{
				System.out.println("raj exception in turning GPS on: "+ex);
				showSettingsAlert();
			}
		}
		
		int currentapiVersion = android.os.Build.VERSION.SDK_INT;
		System.out.println("raj Android version: "+currentapiVersion);
		

		loginbtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub				
				
				if(loginbtn.getText().equals("Logout"))
				{
					Intent service = new Intent(getApplicationContext(), TrackingService.class);
					stopService(service);
					loginbtn.setText("Login");
					passwordet.setEnabled(true);
					passwordet.setVisibility(View.VISIBLE);
					saveIsTrackingStarted(false);
					return;
				}
				
				if(!isGPSEnabled())
				{
					try
					{
						Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
						intent.putExtra("enabled", true);
						sendBroadcast(intent);
						turnGPSOn();
					}
					catch(Exception ex)
					{
						System.out.println("raj exception in turning GPS on: "+ex);
						showSettingsAlert();
					}
					return;
				}

				if (password != null) {
					userString = usernameet.getText().toString();
					passString = passwordet.getText().toString();
					

					Log.d(UNAME, "name usernaemstr=" + userString);
					Log.d(UNAME, "name passwordstr=" + passString);
					Log.d(UNAME, "name usernaem=" + username);
					Log.d(UNAME, "name password=" + password);

					if (passString.equals(password)) {
						
//							Intent login_intent = new Intent(
//									getApplicationContext(),
//									DisplayMapView.class);
//							login_intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
//									| Intent.FLAG_ACTIVITY_NEW_TASK);
//							
//							startActivity(login_intent);
						loginbtn.setText("Logout");
						Intent service = new Intent(getApplicationContext(), TrackingService.class);
						startService(service);
						saveIsTrackingStarted(true);
						passwordet.setEnabled(false);
						passwordet.setVisibility(View.INVISIBLE);
						displayTrackStartedDialog();
						//startActivity(new Intent(getApplicationContext(), DisplayMapView.class));//17.3836256,78.428196

					} 
					else {

						AlertDialog.Builder adb = new AlertDialog.Builder(
								LoginPage.this);
						adb.setTitle("Error Message");
						adb.setMessage("Password is wrong");

						adb.setPositiveButton("ok",
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										// TODO Auto-generated method stub

										usernameet.setText("");
										passwordet.setText("");

									}
								});

						adb.create();
						adb.show();
					}
				} 
			}
		});

		registerbtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				System.out.println("raj llllllllllllllllll");
				if (password == null) {

					System.out.println("raj mmmmmmmmmmmmmmmmmm");
					Intent login_intent = new Intent(LoginPage.this,
							RegisterPage.class);
					System.out.println("raj nnnnnnnnnnnnnnnnnnn");
					
					startActivity(login_intent);

					System.out.println("raj ooooooooooooooooooo");
				}

			}
		});
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.onBackPressed();
		finish();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		usernameet.setText("");
		passwordet.setText("");
		SharedPreferences prefs = getSharedPreferences("ENIGHA_DETAILS", MODE_PRIVATE);
		password = prefs.getString(PASS, null);
		
		if(isTrackingStarted())
		{
			loginbtn.setText("Logout");
			passwordet.setVisibility(View.INVISIBLE);
		}

		if (password != null) {
			loginbtn.setEnabled(true);
			loginbtn.setBackgroundResource(R.drawable.register_button);
			registerbtn.setBackgroundResource(R.drawable.login_button);
			registerbtn.setVisibility(View.GONE);
			ImageView new_to_enigha = (ImageView)findViewById(R.id.imageView2);
			new_to_enigha.setVisibility(View.GONE);
		} else {
			loginbtn.setEnabled(false);
		}
	}
	public void saveIsTrackingStarted(boolean isTrackingStarted)
	{
		SharedPreferences prefs = getSharedPreferences("ENIGHA_DETAILS", MODE_PRIVATE);
		Editor editor = prefs.edit();
		editor.putBoolean("isTrackingStarted", isTrackingStarted);
		editor.commit();
	}
	public boolean isTrackingStarted()
	{
		SharedPreferences prefs = getSharedPreferences("ENIGHA_DETAILS", MODE_PRIVATE);
		return prefs.getBoolean("isTrackingStarted", false);
	}
	public boolean isGPSEnabled()
    {
    	LocationManager mlocManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);;
        boolean enabled = mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        return enabled;
    }
	public void turnGPSOn() {

		String provider = Settings.Secure.getString(getContentResolver(),
				Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
		if (!provider.contains("gps")) {
			final Intent poke = new Intent();
			poke.setClassName("com.android.settings",
					"com.android.settings.widget.SettingsAppWidgetProvider");
			poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
			poke.setData(Uri.parse("3"));
			sendBroadcast(poke);
		}
	}

	private void turnGPSOff() {
		String provider = Settings.Secure.getString(getContentResolver(),
				Settings.Secure.LOCATION_PROVIDERS_ALLOWED);

		if (provider.contains("gps")) { 
			final Intent poke = new Intent();
			poke.setClassName("com.android.settings",
					"com.android.settings.widget.SettingsAppWidgetProvider");
			poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
			poke.setData(Uri.parse("3"));
			sendBroadcast(poke);
		}
	}
	public void showSettingsAlert(){
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
      
        // Setting Dialog Title
        alertDialog.setTitle("GPS settings");	  	        
        alertDialog.setMessage("GPS is not enabled! eNigha Application needs GPS for tracking the location.\n" +
        		"Do you want to enable?");	  
        
        alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivity(intent);
            }
        });
  
        // on pressing cancel button
        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
            }
        });
  
        // Showing Alert Message
        alertDialog.setCancelable(false);
        alertDialog.show();
    }
	public void displayTrackStartedDialog(){
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
      
        // Setting Dialog Title
        alertDialog.setTitle("eNiGHA");	  	        
        alertDialog.setMessage("Tracking started. Do you want to EXIT the application.");	  
        
        alertDialog.setPositiveButton("Exit", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {
            	finish();
            }
        });
  
        // on pressing cancel button
        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
            }
        });
  
        // Showing Alert Message
        alertDialog.setCancelable(false);
        alertDialog.show();
    }
	
}
